package com.twotiger.and.activity.project;

import java.util.HashMap;
import java.util.Map;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import app.twotiger.p2p.R;
import app.twotiger.p2p.R.color;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.twotiger.and.Constants;
import com.twotiger.and.activity.WebViewPage;
import com.twotiger.and.activity.base.BaseActivity;
import com.twotiger.and.activity.base.BaseHandler;
import com.twotiger.and.activity.base.SubTitle;
import com.twotiger.and.activity.user.LoginPage;
import com.twotiger.and.bean.Basebean;
import com.twotiger.and.bean.BroswerUrl;
import com.twotiger.and.bean.Order;
import com.twotiger.and.bean.ProjectdetailData;
import com.twotiger.and.util.ArithUtils;
import com.twotiger.and.util.LogUtil;
import com.twotiger.and.util.PromptManager;
import com.twotiger.and.util.URLUtil;
import com.twotiger.and.util.PromptManager.ReChargeClickListener;
import com.twotiger.and.util.ScreenUtils;
import com.twotiger.and.util.ViewUtils;
import com.twotiger.and.view.SpringProgressView;
import com.view.pulltorefresh.PullToRefreshBase;
import com.view.pulltorefresh.PullToRefreshScrollView;

/**
 * 项目详情
 * @Description: 
 * intent需要携带 PROJECT_Id or PROJECT_DETAIL
 * @Author douxy
 * @Date 2015年8月12日 下午2:43:22
 */
public class ProjectDetailPage extends BaseActivity implements OnClickListener {

    protected static final int OPENPAYMENTSUCCES = 0;
    protected static final int OPENPAYMENTFAIL = 1;

    private static final int GETDETAILSUCCES = 2;
    private static final int GETDETAILFAIL = 3;

    /**投资流程各个页面启动标志*/
    public static final int TENDERREQUEST = 20;
    /**投资流程各个页面关闭的标示(投资成功)*/
    public static final int TENDERRESULTCLOSE_SUC = 21;
    /**投资流程各个页面关闭的标示(投资失败)*/
    public static final int TENDERRESULTCLOSE_FAI = 22;

    private String projectId;
    private static HashMap<String, String> params;
    private static Handler handler;
    //公用组件
    private ProjectdetailData projectDetail;
    private Order order;
    //公用布局
    private SubTitle subTitle;
    private Button to_inverst;

    private RelativeLayout rl_active;
    private TextView project_activity;
    private TextView project_detail_yeild;
    private TextView project_detail_award_yield;
    private TextView repayment_value;
    private TextView recycle_value;
    private TextView project_detail_amount;
    private TextView project_detail_remainder;

    private ProjectCommingJob projectCommingJob;
    private String mode;
    private PullToRefreshScrollView project_detail_sc;
    private TextView tv_assignmsg, tv_count_down;
    private RelativeLayout rl_progress;
    private SpringProgressView progress_bar_new;
    private TextView project_detail_progress_tv;
    private RelativeLayout rl_detail_xmgk, rl_detail_bxbz, rl_detail_hkjh, rl_detail_tzjl;

    @Override
    protected View loadViewLayout(LayoutInflater inflater) {
        View view = inflater.inflate(R.layout.project_detail_layout, null);

        return view;
    }

    @Override
    protected void findViewById(View view) {
        subTitle = new SubTitle(view) {
            @Override
            protected void clickTitle(View v) {
            }

            @Override
            protected void clickRightBtn(View v) {
            }

            @Override
            protected void cickLeftBtn(View v) {
                onBackPress();
            }
        };
        to_inverst = (Button) view.findViewById(R.id.to_inverst);
        subTitle.setTitle("项目详情");
        subTitle.hideBtns();
        subTitle.hideBottomLine();
        tintManager.setTintResource(R.drawable.bg_account_statusbar);
        subTitle.setBgResource(R.drawable.bg_account_title);
        subTitle.setColor(getResources().getColor(color.white));
        subTitle.title_left_bt.setVisibility(View.VISIBLE);
        subTitle.title_left_bt.setImageResource(R.drawable.back_w);
        subTitle.title_left_bt.setVisibility(View.VISIBLE);

        rl_active = (RelativeLayout) view.findViewById(R.id.rl_active);
        project_activity = (TextView) view.findViewById(R.id.project_activity);
        rl_progress = (RelativeLayout) view.findViewById(R.id.rl_progress);
        project_detail_progress_tv = (TextView) view.findViewById(R.id.project_detail_progress_tv);
        progress_bar_new = (SpringProgressView) view.findViewById(R.id.progress_bar_new);
        progress_bar_new.setMaxCount(100);

        project_detail_yeild = (TextView) view.findViewById(R.id.project_detail_yeild);
        project_detail_award_yield = (TextView) view.findViewById(R.id.project_detail_award_yield);
        repayment_value = (TextView) view.findViewById(R.id.repayment_value);
        recycle_value = (TextView) view.findViewById(R.id.recycle_value);
        project_detail_amount = (TextView) view.findViewById(R.id.project_detail_amount);
        project_detail_remainder = (TextView) view.findViewById(R.id.project_detail_remainder);
        project_detail_sc = (PullToRefreshScrollView) view.findViewById(R.id.project_detail_sc);
        tv_assignmsg = (TextView) view.findViewById(R.id.tv_assignmsg);
        tv_count_down = (TextView) view.findViewById(R.id.tv_count_down);
        rl_detail_xmgk = (RelativeLayout) view.findViewById(R.id.rl_detail_xmgk);
        rl_detail_bxbz = (RelativeLayout) view.findViewById(R.id.rl_detail_bxbz);
        rl_detail_hkjh = (RelativeLayout) view.findViewById(R.id.rl_detail_hkjh);
        rl_detail_tzjl = (RelativeLayout) view.findViewById(R.id.rl_detail_tzjl);

//        View fl_inner = project_detail_sc.findViewById(R.id.fl_inner);
//        fl_inner.setBackgroundColor(getResources().getColor(app.twotiger.p2p.R.color.bg_1));

    }

    /**
     * 填充数据
     */
    private void fillData() {
        //立即投资按钮
        if (projectDetail.getStatus() == Constants.PRO_STATUS_WAITING) {//倒计时
            tv_count_down.setVisibility(View.VISIBLE);
            projectCommingJob = new ProjectCommingJob();
            projectCommingJob.start();
            to_inverst.setText(projectDetail.getStatusName());
            to_inverst.setBackgroundResource(R.color.gray_1);
        } else if (projectDetail.getStatus() != Constants.PRO_STATUS_TRADING) {
            switch (projectDetail.getStatus()) {
            case Constants.PRO_STATUS_FULFILL: // 募集完成（ 已满标/待复审）
            case Constants.PRO_STATUS_CHECK_WAIT: // 募集完成（复审通过/数据处理中）
                to_inverst.setText(projectDetail.getStatusName());
                to_inverst.setBackgroundResource(R.color.gray_1);
                break;
            case Constants.PRO_STATUS_CHECKED: // 还款中（复审通过/还款中） 
            case Constants.PRO_STATUS_REPAYING: // 还款中（还款中/数据处理中）；
            case Constants.PRO_STATUS_REPAYMENT_EARLY: // 还款中（提前还款）
                to_inverst.setText(projectDetail.getStatusName());
                to_inverst.setBackgroundResource(R.color.gray_1);
                break;
            case Constants.PRO_STATUS_REPAYMENT: //已还款（正常还款）
            case Constants.PRO_STATUS_REPAYMENT_LATE: // 已还款（逾期还款）
                to_inverst.setText(projectDetail.getStatusName());
                to_inverst.setBackgroundResource(R.color.gray_1);
                break;
            case Constants.PRO_STATUS_LATE: // 逾期（逾期）
                to_inverst.setText(projectDetail.getStatusName());
                to_inverst.setBackgroundResource(R.color.gray_1);
                break;

            default:
                break;
            }

        }
        subTitle.setTitle(projectDetail.getName());

        if (projectDetail.getActivityMark() == 0) { //无活动
            rl_active.setVisibility(View.INVISIBLE);
            project_activity.setVisibility(View.GONE);
        } else {
            rl_active.setVisibility(View.VISIBLE);
            project_activity.setText(projectDetail.getActivityName());
        }

        try {
            int screenWidth = ScreenUtils.getScreenWidth(ProjectDetailPage.this);
            int completeLv = Integer.parseInt(projectDetail.getCompleteLv());
            int pw = progress_bar_new.getMeasuredWidth();
            int rw = rl_progress.getMeasuredWidth();
            int dd = (int) ArithUtils.div((screenWidth - pw), 2, 10);
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            int aa = (int) ArithUtils.mul(ArithUtils.div(completeLv, 100, 10), pw);
            int bb = (int) ArithUtils.div(rw, 2, 10);
            int cc = dd + aa - bb;
            layoutParams.setMargins(cc, 0, 0, 0);//4个参数按顺序分别是左上右下
            rl_progress.setLayoutParams(layoutParams);
            progress_bar_new.setCurrentCount(completeLv);
            project_detail_progress_tv.setText(completeLv + "");
            if (completeLv == 100) {
                layoutParams.setMargins(cc - 5, 0, 0, 0);//4个参数按顺序分别是左上右下
                rl_progress.setLayoutParams(layoutParams);
            }
        } catch (Exception e) {

        }

        project_detail_yeild
            .setText(ArithUtils.formatProject(projectDetail.getYield(), "#.#") + "");//保留一位小数 ArithUtils.trim(projectDetail.getYield())
        if (projectDetail.getAwardYield() > 0) {
            project_detail_award_yield.setText("+"
                                               + ArithUtils.formatProject(
                                                   projectDetail.getAwardYield(), "#.##") + "%");//ArithUtils.trim(1 * projectDetail.getAwardYield())
        } else {
            project_detail_award_yield.setVisibility(View.GONE);
        }
        repayment_value.setText(projectDetail.getRepayTypeName());
        recycle_value.setText(projectDetail.getPeriod() + "");

        if ("0".equals(projectDetail.getAssignMark())) {
            tv_assignmsg.setText("");
        } else if ("1".equals(projectDetail.getAssignMark())) {
            tv_assignmsg.setText(projectDetail.getAssignMsg());
        }

        project_detail_amount.setText(ArithUtils.coverMoneyComma("" + projectDetail.getAmount()));
        project_detail_remainder.setText("剩余可投："
                                         + ArithUtils.coverMoneyComma(("" + projectDetail
                                             .getRemainAmount())));
    }

    public void openpayment() {
        params.clear();
        params.put("token", getToken());
        getDate(params, Constants.REGISTHF, handler, OPENPAYMENTSUCCES, OPENPAYMENTFAIL, true,
            true, false);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
        case R.id.rl_detail_xmgk:
            if (ViewUtils.isFastDoubleClick(view)) {
                return;
            }
            if (projectDetail == null) {
                return;
            }
            //跳到活动页面
            Intent xmgk = new Intent();
            xmgk.setClass(mContext, WebViewPage.class);
            xmgk.putExtra("title", "项目概况");
            Map<String, String> contractmap = new HashMap<String, String>();
            contractmap.put("proType", "xmgk");
            contractmap.put("projectId", projectDetail.getProjectId());
            contractmap.put("token", getToken());
            contractmap.put("type", projectDetail.getType());
            contractmap.put("mode", projectDetail.getMode());
            xmgk.putExtra("url",
                Constants.PRODETAILHTML + "?" + URLUtil.createContractUrl(contractmap, "3.0"));
            xmgk.putExtra("PROJECTDETAIL", projectDetail);
            startNewActivity(xmgk, R.anim.push_left_in, R.anim.push_left_out, false);
            break;
        case R.id.rl_detail_bxbz:
            if (ViewUtils.isFastDoubleClick(view)) {
                return;
            }
            if (projectDetail == null) {
                return;
            }
            //跳到活动页面
            Intent bxbz = new Intent();
            bxbz.setClass(mContext, WebViewPage.class);
            bxbz.putExtra("title", "本息保障");
            Map<String, String> contractmap_bxbz = new HashMap<String, String>();
            contractmap_bxbz.put("proType", "bxbz");
            contractmap_bxbz.put("projectId", projectDetail.getProjectId());
            contractmap_bxbz.put("token", getToken());
            contractmap_bxbz.put("type", projectDetail.getType());
            contractmap_bxbz.put("mode", projectDetail.getMode());
            bxbz.putExtra("url",
                Constants.PRODETAILHTML + "?" + URLUtil.createContractUrl(contractmap_bxbz, "3.0"));
            bxbz.putExtra("PROJECTDETAIL", projectDetail);
            startNewActivity(bxbz, R.anim.push_left_in, R.anim.push_left_out, false);
            break;
        case R.id.rl_detail_hkjh:
            if (ViewUtils.isFastDoubleClick(view)) {
                return;
            }
            if (projectDetail == null) {
                return;
            }
            //跳到活动页面
            Intent hkjh = new Intent();
            hkjh.setClass(mContext, WebViewPage.class);
            hkjh.putExtra("title", "还款计划");
            Map<String, String> contractmap_hkjh = new HashMap<String, String>();
            contractmap_hkjh.put("proType", "hkjh");
            contractmap_hkjh.put("projectId", projectDetail.getProjectId());
            contractmap_hkjh.put("token", getToken());
            contractmap_hkjh.put("type", projectDetail.getType());
            contractmap_hkjh.put("mode", projectDetail.getMode());
            hkjh.putExtra("url",
                Constants.PRODETAILHTML + "?" + URLUtil.createContractUrl(contractmap_hkjh, "3.0"));
            hkjh.putExtra("PROJECTDETAIL", projectDetail);
            startNewActivity(hkjh, R.anim.push_left_in, R.anim.push_left_out, false);
            break;
        case R.id.rl_detail_tzjl:
            if (ViewUtils.isFastDoubleClick(view)) {
                return;
            }
            if (projectDetail == null) {
                return;
            }
            //跳到活动页面
            Intent tzjl = new Intent();
            tzjl.setClass(mContext, WebViewPage.class);
            tzjl.putExtra("title", "投资记录");
            Map<String, String> contractmap_tzjl = new HashMap<String, String>();
            contractmap_tzjl.put("proType", "tzjl");
            contractmap_tzjl.put("projectId", projectDetail.getProjectId());
            contractmap_tzjl.put("token", getToken());
            contractmap_tzjl.put("type", projectDetail.getType());
            contractmap_tzjl.put("mode", projectDetail.getMode());
            tzjl.putExtra("url",
                Constants.PRODETAILHTML + "?" + URLUtil.createContractUrl(contractmap_tzjl, "3.0"));
            tzjl.putExtra("PROJECTDETAIL", projectDetail);
            startNewActivity(tzjl, R.anim.push_left_in, R.anim.push_left_out, false);
            break;
        case R.id.rl_active:
            if (ViewUtils.isFastDoubleClick(view)) {
                return;
            }
            //跳到活动页面
            Intent in1 = new Intent();
            in1.setClass(mContext, WebViewPage.class);
            in1.putExtra("title", "活动详情");
            in1.putExtra("url", projectDetail.getActivityUrl());
            in1.putExtra("BACK_MODE", WebViewPage.BACK_DIRECT); //webview的返回形式
            startNewActivity(in1, R.anim.push_left_in, R.anim.push_left_out, false);
            break;
        case R.id.to_inverst:

            if (ViewUtils.isFastDoubleClick(view)) {
                return;
            }
            if (projectDetail == null) {
                return;
            }
            if (projectDetail.getStatus() != Constants.PRO_STATUS_TRADING) {
                return;
            }
            if (!isLogin()) {
                Intent intent = new Intent(ProjectDetailPage.this, LoginPage.class).putExtra(
                    "FROM", R.id.to_inverst);
                startNewActivity(intent, R.anim.slide_in_from_bottom, R.anim.silent_anim, false);
                return;
            }
            if (!hasOpenThirdAct()) {
                PromptManager.showConfirmAlertCommon(ProjectDetailPage.this, 0, "",
                    "您还未开通汇付天下托管账号，继续开通", "取消", "继续", true, new ReChargeClickListener() {

                        @Override
                        public void onClickConfirm() {

                        }

                        @Override
                        public void onClickCancel() {
                            // 确认，则继续
                            openpayment();
                        }
                    });
                return;
            }
            if (projectDetail.getAmount() != 0) {
                order = new Order();
                order.setProjectid(projectDetail.getProjectId());
                order.setProjectname(projectDetail.getName());
                order.setProject_yield(projectDetail.getYield() + projectDetail.getAwardYield());
                order.setRecyle(projectDetail.getPeriod());
                order.setRepaymenttype(projectDetail.getRepayTypeName());
                order.setStartrepytime(projectDetail.getEndInterestDate());
                order.setStartyidtime(projectDetail.getStartInterestDate());
                order.setCaninverst(Double.parseDouble(projectDetail.getRemainAmount()));
                order.setpType(projectDetail.getpType());
                order.setMinInvest(projectDetail.getMinInvest());
                order.setMaxInvest(projectDetail.getMaxInvest());

                order.setType(projectDetail.getType());
                order.setMode(projectDetail.getMode());

                Intent intent = new Intent(mContext, InverstInputAmountPage.class).putExtra(
                    "ORDER", order);
                startNewActivityforresult(intent, R.anim.slide_in_from_bottom, R.anim.silent_anim,
                    TENDERREQUEST);

            }
            break;
        }
    }

    @Override
    protected void onActivityResult(int requestcode, int resultcode, Intent intent) {
        super.onActivityResult(requestcode, resultcode, intent);
        if (requestcode == TENDERREQUEST) {
            if (resultcode == TENDERRESULTCLOSE_SUC) {
                //                finish();
            }
        }
    }

    @Override
    protected void setListener() {
        to_inverst.setOnClickListener(this);
        rl_active.setOnClickListener(this);
        rl_detail_xmgk.setOnClickListener(this);
        rl_detail_bxbz.setOnClickListener(this);
        rl_detail_hkjh.setOnClickListener(this);
        rl_detail_tzjl.setOnClickListener(this);

        handler = new BaseHandler(this) {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                case OPENPAYMENTSUCCES:
                    Basebean result_opoen = JSONObject
                        .parseObject((String) msg.obj, Basebean.class);
                    if (result_opoen.isOk()) {
                        BroswerUrl responseinfo = JSONObject.parseObject(result_opoen.data,
                            BroswerUrl.class);
                        Intent intent = new Intent(ProjectDetailPage.this, WebViewPage.class);
                        intent.putExtra("title", "开通三方托管账户");
                        intent.putExtra("url", responseinfo.getUrl());
                        intent.putExtra("BUSINESS_TYPE", WebViewPage.TYPE_PAYMENT_REGIST);
                        startNewActivity(intent, R.anim.push_left_in, R.anim.push_left_out, false);
                    }
                    break;
                case OPENPAYMENTFAIL:
                    showToast("网络异常");
                    break;
                case GETDETAILSUCCES:
                    Basebean result = JSONObject.parseObject((String) msg.obj, Basebean.class);
                    if (result.isOk()) {
                        ProjectdetailData ttt = JSON.parseObject(result.data,
                            ProjectdetailData.class);
                        projectDetail = ttt;
                        fillData();
                    } else {
                        showToast(result.codeDesc);
                    }
                    project_detail_sc.onRefreshComplete();
                    break;
                case GETDETAILFAIL:
                    project_detail_sc.onRefreshComplete();
                    showToast("网络异常");
                    break;
                default:
                    break;
                }

                super.handleMessage(msg);
            }
        };

        project_detail_sc
            .setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ScrollView>() {

                @Override
                public void onPullDownToRefresh(PullToRefreshBase<ScrollView> refreshView) {
                    getProjectDetail();
                }

                @Override
                public void onPullUpToRefresh(PullToRefreshBase<ScrollView> refreshView) {

                }
            });
    }

    @Override
    protected void processLogic() {
        params = getParm();
        projectId = getIntent().getStringExtra("PROJECT_ID");
        mode = getIntent().getStringExtra("MODE");
        projectDetail = (ProjectdetailData) getIntent().getSerializableExtra("PROJECT_DETAIL");
        if (projectDetail != null && projectDetail.getProjectId() != null) {
            fillData();
        } else if (projectId != null && mode != null) {
            getProjectDetail();
        } else {
            showToast("缺少必要信息!!");
            onBackPress();
        }
    }

    private void getProjectDetail() {
        params.clear();
        params.put("projectId", projectId);
        params.put("type", Constants.TYPE_NID_ZHITOU);
        params.put("mode", mode);
        params.put("token", getToken());
        getDate(params, Constants.PROJECTINFOQUERY, handler, GETDETAILSUCCES, GETDETAILFAIL, true,
            true, true);
    }

    @Override
    protected void onBackPress() {
        finish();
        overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (projectCommingJob != null) {
            projectCommingJob.stop();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (projectCommingJob != null) {
            projectCommingJob = new ProjectCommingJob();
            projectCommingJob.start();
        }
    }

    @Override
    protected void onRestart() {
        if (projectDetail != null) {
            if (!isNewMan() && Constants.PRO_TYPE_NEWER.equals(projectDetail.getMode())) { //用户登录之后判断其是否可投新手项目，不可则直接finish掉本页面
                finish();
            }
        }
        super.onRestart();
    }

    class ProjectCommingJob implements Runnable {

        /**每个县城只能start一次*/
        private boolean isRun = false;
        private boolean stop = false;

        public void stop() {
            this.stop = true;
        }

        public void start() {
            if (isRun)
                return;
            isRun = true;
            stop = false;
            handler.post(this);
        }

        @Override
        public void run() {
            LogUtil.info(ProjectCommingJob.class, "project: " + projectDetail.getTime2Start());
            //            to_inverst.setText("倒计时 : " + projectDetail.getTime2Start());
            tv_count_down.setText("距离开始时间: " + projectDetail.getTime2Start());
            if (stop) {
                return;
            }
            if (projectDetail.getStatus() == Constants.PRO_STATUS_WAITING) {
                handler.postDelayed(this, 1000);
            }
        }
    }
}
